//
//  NeoNuiTranslation.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/4/8.
//

import UIKit

class NeoNuiTranslation: NSObject {
    
    /// 翻译
    /// - Parameters:
    ///   - from: 原文语言类型
    ///   - to: 目标语言类型
    ///   - text: 原文
    ///   - completion: 0:原文 1:翻译结果
    static func translation(from: String, to: String, text: String, completion: @escaping (_ sourceText: String?, _ result: String?) -> Void) {
        let target = OtherAPI.translation(from: from, to: to, text: text)
        YLRequest.request(target) { result in
            switch result {
            case .success(let res):
                let dataArray = res.dataArray
                let translationResult = NeoNuiTranslationDataModel.parseTranslationResult(dataArray: dataArray)
                completion(translationResult.0, translationResult.1)
                
            case .failure:
                completion(nil, nil)
            }
        }
    }
    
    
    static func translations(from: String, to: String, text: String, completion: @escaping ([NeoNuiTranslationResultModel]) -> Void) {
        let target = OtherAPI.translation(from: from, to: to, text: text)
        YLRequest.request(target) { result in
            switch result {
            case .success(let res):
                let dataArray = res.dataArray
                let translationResults = NeoNuiTranslationDataModel.parseTranslationResults(dataArray)
                completion(translationResults)
                
            case .failure:
                completion([])
            }
        }
    }
    
    static func translations(id: Int, from: String, to: String, text: String, completion: @escaping (Int, [NeoNuiTranslationResultModel]) -> Void) {
        let target = OtherAPI.translation(from: from, to: to, text: text)
        YLRequest.request(target) { result in
            switch result {
            case .success(let res):
                let dataArray = res.dataArray
                let translationResults = NeoNuiTranslationDataModel.parseTranslationResults(dataArray)
                completion(id, translationResults)
                
            case .failure:
                completion(id, [])
            }
        }
    }
    
    
}


class NeoNuiTranslationDataModel: BaseModel {
    
    /// 段落排序
    var order: Int = 0
    var sentences: [NeoNuiTranslationSentencesModel] = []
    
    static func parseTranslationResult(dataArray: [Any]) -> (String, String) {
        
        let models = JsonUtil.modelsFromArray(dataArray, NeoNuiTranslationDataModel.self)
        
        // 根据 order 排序
        let modelSorted = models.sorted { $0.order < $1.order }
        
        var result = ""
        var sourceText = ""
        
        for model in modelSorted {
            let sentences = model.sentences.sorted { $0.order < $1.order }
            let res = sentences.map { $0.data }.joined(separator: "")
            result.append(res)
            result.append("\n")
            
            let st = sentences.map { $0.contrastSourceText }.joined(separator: "")
            sourceText.append(st)
            sourceText.append("\n")
        }
        
        if result.hasSuffix("\n") {
            result = String(result.dropLast(1))
        }
        
        if sourceText.hasSuffix("\n") {
            sourceText = String(sourceText.dropLast(1))
        }
        
        return (sourceText, result)
    }
    
    static func parseTranslationResults(_ dataArray: [Any]) -> [NeoNuiTranslationResultModel] {
        
        let models = JsonUtil.modelsFromArray(dataArray, NeoNuiTranslationDataModel.self)
        
        // 根据 order 排序
        let modelSorted = models.sorted { $0.order < $1.order }
        
        var results: [NeoNuiTranslationResultModel] = []
        
        for model in modelSorted {
            let sentences = model.sentences.sorted { $0.order < $1.order }
            
            results.appends(sentences.map { sentence in
                return NeoNuiTranslationResultModel(
                    sourceText: sentence.contrastSourceText,
                    transText: sentence.data
                )
            })
            
        }
        
        return results
    }
    
}

class NeoNuiTranslationSentencesModel: BaseModel {
    
    /// 段落排序
    var order: Int = 0
    /// 翻译结果
    var data: String = ""
    /// 原文本
    var contrastSourceText: String = ""
    
}

class NeoNuiTranslationResultModel: BaseModel {
    
    var sourceText: String = ""
    var transText: String = ""
    
    init(sourceText: String, transText: String) {
        self.sourceText = sourceText
        self.transText = transText
    }
    
    required init() {
        fatalError("init() has not been implemented")
    }
    
}


class NeoNuiResultModel: BaseModel {
    // 使用时间戳做 id
    var id: Int = 0
    // 记录原文的语言类型
    var language: NeoNuiType = .zh
    
    var zhText: String = ""
    var ruText: String = ""
    
     init(language: NeoNuiType, zhText: String, ruText: String) {
         self.language = language
         self.zhText = zhText
         self.ruText = ruText
         self.id = Date.sg.timestamp()
    }
    
    required init() {
        fatalError("init() has not been implemented")
    }
    
}
